<?php
//员工
namespace app\crmindex\controller;

use app\crm\model\Sn;
use app\crm\model\StaffAccessory;
use app\crmindex\model\Sys;
use app\crmindex\model\WechaUrl;
use think\cache\driver\Memcache;
use think\Db;
use think\Request;
use think\Exception;
use app\crm\model\Staff as StaffModel;
use weworkapi\api\datastructure\user\User;
use weworkapi\api\src\API;
use weworkapi\api\src\CorpAPI;

class Staff extends \LoginController
{
    ///////////////////////////////////////////////////////////////////////////
    ///前台获取页面数据接口
    /// 1.登录接口
    ///
    ///////////////////////////////////////////////////////////////////////////
    function token(){
        $TOKEN  = $this->generateToken();
        $Memcache = new Memcache();
        $Memcache->set($TOKEN,'SuiYueRuSuo');
        p($TOKEN);
    }
    /**
     * 登录接口
     *接口地址 xlt.shared123.cn/crmindex/staff/login
     * @post
     *| 参数 | 参数类型 | 是否必须 | 备注 |
     *| username | var | 1 | 账号 |
     *| password | var | 1 | 密码 |
     */
    public function login($username, $password, $platform = '')
    {
        try {
            $StaffModel = new \app\crmindex\model\Staff();
            empty($username)&&\exception('账号不能为空');
            $user = $StaffModel->field('staff_id,staff_name,user_name,password,salt,phone,is_login')
                ->where('user_name', $username)
                ->whereOr('staff_name',$username)
                ->whereOr('phone',$username)
                ->find();

            empty($user) && \exception('用户名不存在');
            $user->is_login === 0 && \exception('用户不可用');
            $passwordUser = md5($password . $user->salt);
            $passwordUser === $user->password || \exception('密码错误');
            // 登录成功
            // 生成token & 更新最后登录时间
            $TOKEN  = $this->generateToken();
            $Memcache = new Memcache();
            $Memcache->set($TOKEN,$user['staff_id']);
            $lastLoginKey = 'last_login';
            $tokenKey = 'token';
            if (in_array($platform, config('platform'))) {
                $lastLoginKey .= "_{$platform}";
                $tokenKey .= "_{$platform}";
            }
            $data = [
                $lastLoginKey => time(),
                $tokenKey => $TOKEN,
            ];
            $StaffModel->save($data, [
                'staff_id' => $user->staff_id,
            ]);

            $user->setAttr('token', $data[$tokenKey]);
            unset($user->password);
            unset($user->salt);
            $this->successTerminate($user);

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 获取staff详细信息
     *接口地址 xlt.shared123.cn/crmindex/staff/staffInfo
     * @post
     *| 参数 | 参数类型 | 是否必须 | 备注 |
     *| staff_id | var | 1 | staff_id |
     *
     * staff_id,staff_sn,staff_name,staff_name,user_name,is_downstream
    `staff_id`
    `staff_sn`       '员工编号',
    `staff_name`     '员工姓名',
    `user_name`      '登录账号',
    `password`       '密码',
    `department_id`  '所属部门id',
    `entry_time`     '入职时间',
    `sex`            '性别 1男 0女',
    `phone`          '手机',
    `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
    `duty` varchar(100) DEFAULT NULL COMMENT '职务',
    `superior_id` varchar(64) DEFAULT NULL COMMENT '直属上级',
    `is_login` tinyint(1) DEFAULT '0' COMMENT '是否允许登录 1是 0否',
    `birthday` int(11) DEFAULT NULL COMMENT '生日',
    `special_plane` varchar(100) DEFAULT NULL COMMENT '座机',
    `qq` varchar(20) DEFAULT NULL COMMENT 'qq',
    `emergency_contact` varchar(20) DEFAULT NULL COMMENT '紧急联系人',
    `emergency_contact_plane` varchar(50) DEFAULT NULL COMMENT '紧急联系人电话',
    `education_background` varchar(100) DEFAULT NULL COMMENT '学历',
    `school` varchar(255) DEFAULT NULL COMMENT '学校',
    `time_property` varchar(10) DEFAULT NULL COMMENT '生肖',
    `constellation` varchar(50) DEFAULT NULL COMMENT '星座',
    `blood_type` varchar(50) DEFAULT NULL COMMENT '血型',
    `number_id` varchar(50) DEFAULT NULL COMMENT '身份证号',
    `unmber_location` varchar(100) DEFAULT NULL COMMENT '户口所在地',
    `unmber_location_address` varchar(255) DEFAULT NULL COMMENT '户口所在地地址',
    `home_location` varchar(255) DEFAULT NULL COMMENT '家庭住址',
    `home_location_address` varchar(255) DEFAULT NULL COMMENT '家庭详细住址',
    `personnel_evaluate` varchar(255) DEFAULT NULL COMMENT '人事点评',
    `salt` varchar(255) DEFAULT NULL COMMENT '登录盐',
    `dimission_type` tinyint(1) DEFAULT '0' COMMENT '0在职 1离职',
    `login_lock` tinyint(1) DEFAULT '0' COMMENT '锁定登录控制 1锁定 0解除锁定',
    `sys_custodian` tinyint(1) DEFAULT '0' COMMENT '是否是系统管理员 0不是 1是',
    `head_img` text COMMENT '头像',
    `attention_type` tinyint(1) unsigned DEFAULT '0' COMMENT '1已关注 0未关注',
    `is_audit` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0未审核 1已审核',
    `is_downstream` tinyint(1) NOT NULL DEFAULT '0' COMMENT '0下游成员 1员工',
    `last_login` int(11) DEFAULT NULL COMMENT '最后登录时间',
    `token` varchar(255) DEFAULT NULL COMMENT 'token',
     */
    public function staffInfo(){
        try {
            $request = request();
            $userId = $request->header('userId');

            $Staff = new \app\crmindex\model\Staff();
            $data = $Staff->getInfo($userId);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }

    }
    public function dynamicInfo(){
        $argc['redirectUrl'] = 'http://xlt.shared123.cn/crmindex/staff/dynamicInfo2';
        $argc['state'] = $_GET['state'];
        $a= $this->qiyeweixin->getCodeRedirectUrl($argc);
        echo "<SCRIPT LANGUAGE='javascript'>";
        echo "location.href='$a'";
        echo "</SCRIPT>";
    }
    public function dynamicInfo2(Request $request){

        $code = $request->get('code');
        $state = $request->get('state');
        $Sys = new Sys();
        $dynamic_info_url = $Sys->crm_sys_db()->where('id',1)->value('dynamic_info_url');


        $UserObj = $this->qiyeweixin->GetUserInfoByCode($code);
        $token = $this->generateToken();
        $Memcache = new Memcache();
        $Memcache->set($token,$UserObj->UserId);

        echo "<SCRIPT LANGUAGE='javascript'>";
        if(empty(strstr($dynamic_info_url,'?'))){
            echo "location.href='$dynamic_info_url&token=$token&dynamic_id=$state'";
        }else{
            echo "location.href='$dynamic_info_url&token=$token&dynamic_id=$state'";
        }

        echo "</SCRIPT>";

    }
    public function wlogin(){

       $argc['redirectUrl'] = 'http://xlt.shared123.cn/crmindex/staff/wlogin2';
       $argc['state'] = $_GET['state'];
       $a= $this->qiyeweixin->getCodeRedirectUrl($argc);

        echo "<SCRIPT LANGUAGE='javascript'>";
        echo "location.href='$a'";
        echo "</SCRIPT>";
     //  header("Location: ".$a);
    }
    public function xwloginxx(){

        $argc['redirectUrl'] = 'http://xlt.shared123.cn/crmindex/staff/xwloginxx2';
        $argc['state'] = $_GET['state'];
        $a= $this->qiyeweixin->getCodeRedirectUrl($argc);

        echo "<SCRIPT LANGUAGE='javascript'>";
        echo "location.href='$a'";
        echo "</SCRIPT>";
        //  header("Location: ".$a);
    }
    public function xwloginxx2(Request $request){

        $code = $request->get('code');
        $state = $request->get('state');
        p($code);
    }
    public function wlogin2(Request $request){

        $code = $request->get('code');
        $state = $request->get('state');


        $WechaUrl = new WechaUrl();
        $url = $WechaUrl->wecha_url_db()->where('id_name',$state)->value('url');


        $UserObj = $this->qiyeweixin->GetUserInfoByCode($code);
        $token = $this->generateToken();
        $Memcache = new Memcache();
        $Memcache->set($token,$UserObj->UserId);

        echo "<SCRIPT LANGUAGE='javascript'>";
        if(empty(strstr($url,'?'))){
            echo "location.href='$url&token=$token'";
        }else{
            echo "location.href='$url&token=$token'";
        }

        echo "</SCRIPT>";

    }
    /**
     * 微信登录接口
     *接口地址 xlt.shared123.cn/crmindex/staff/xwlogin
     * @post
     *| 参数 | 参数类型 | 是否必须 | 备注 |
     *| code | var | 1 | 微信获取的code |
     */
    public function xwlogin(Request $request){
        try {
            $request = request();
            $code = $request->get('code');
            $UserObj = $this->qiyeweixin->GetUserInfoByCode($code);
            $token = $this->generateToken();
            $Memcache = new Memcache();
            $Memcache->set($token,$UserObj->UserId);
            $red['token'] = $token;
            $this->successTerminate($red);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    public function text(Request $request){
       $token =  $request->get('token');
       $Memcache = new Memcache();
        $USERiD = $Memcache->get($token);
       p($USERiD);

    }
    //生成token
    protected function generateToken()
    {
        $string = time() . mt_rand(1000000000, 9999999999);
        $string = md5($string);

        return strtoupper($string);
    }

    public function adt(){
       p(234);
    }

    function addxy($staff_id,$staff_name,$phone,$duty){
        import('weworkapi.api.src.CorpApp', EXTEND_PATH,'.php');
        $config = config('qiyeweixin');
        $qiyeweixin =  new CorpAPI($config['CORP_ID'], $config['CONTACT_SYNC_SECRET']);
        $user = new User();
        {
            $Sys = new Sys();
            $crm_sxyhd_did = $Sys->crm_sys_db()->where('id',1)->value('crm_sxyhd_did');

            $user->userid = $staff_id;
            $user->name = $staff_name;//名称
            $user->mobile = $phone;//手机
            $user->department = array($crm_sxyhd_did);//部门
            $user->position = $duty;//职位
            $user->gender = '';//性别
        }
        $qiyeweixin->UserCreate($user);
    }

    public function qywx_login(){
        $code = $_GET['code'];
        $state = $_GET['appid'];
        $data = Db::table('hisi_admin_member')->where('id|as_name',$state)->find();
        session('companyInfo.id',$data['id']);
        if(!$data){
            return json(['error'=>1030,'message'=>'企业号错误']);
        }
        $dbString = sprintf('mysql://%s:%s@%s:%d/%s#utf8', $data['db_username'], $data['db_password'], $data['db_host'], $data['db_port'], $data['db_name']);
        $is_qywx = Db::connect($dbString)->table('em_sys_para')->value('mobile_is_qywx');
        $Sys = new Sys();
        if($is_qywx=='true'){
            $a = new WechatBase('mobile_xxtsSecret',$dbString);
            $access_token =    $a->getAccessToken();
            $oauth2Url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code;
            $wrdataJson = $this->http_request($oauth2Url);
            $wrdata = \GuzzleHttp\json_decode($wrdataJson,true);
            if(!isset($wrdata['UserId'])){
                if(isset($wrdata['errcode'])){

                    return json(['error'=>1030,'message'=>"微信错误！错误代码".$wrdata['errcode']]);
                }else{

                    return json(['error'=>1030,'message'=>'该账号未绑定系统']);

                }
            }

            $UserId = $wrdata['UserId'];
            $userInfo = Db::connect($dbString)->table('em_user')->where('is_w', $UserId)->find();

            if (empty($userInfo)){
                $Sys->getLog(1, 3, 2, $dbString,$userInfo['loginName'],$userInfo['userName']);
                return json(['error'=>1030,'message'=>'应用中没有该用户']);

            }
            //验证用户的状态
            if ($userInfo['workState'] == 1) {
                $Sys->getLog(1, 2, 2, $dbString,$userInfo['loginName'],$userInfo['userName']);
                return json(['error'=>1030,'message'=>'用户已离职']);
            }
            $dbInfo = Db::table('hisi_admin_member')->where('id', $data['id'])->field('db_host,db_port,db_name,db_username as username,db_password as password ')->find();
            $dbString = sprintf('mysql://%s:%s@%s:%d/%s#utf8', $data['db_username'], $data['db_password'], $data['db_host'], $data['db_port'], $data['db_name']);
            $is_qywx = Db::connect($dbString)->table('em_sys_para')->value('mobile_is_qywx');
            if ($is_qywx == 'true') {

                //验证用户的状态
//                $Sys = new Sys();
                $Sys->getLog(0, 0, 2, $dbString,$userInfo['loginName'],$userInfo['userName']);
                unset($userInfo['password']);
                unset($userInfo['salt']);
                \cookie('module', 'emms');
                // 4. 将用户数据|数据库连接信息 加入session
                session('userInfo', $userInfo);
                session('dbInfo', $dbInfo);
                session('is_app',1);
                $data['comp_no'] = $data['id'];
                $sysData = Db::connect($dbString)->table('em_sys_company_info')->find();
                $data['comp_name'] = $sysData['companyName'];
                session('companyInfo', $data);
                $userInfo['companyNo'] = $data['id'];
                $data['comp_name'] = $sysData['companyName'];
                //记录登录信息
                Cookie::forever('compNo', $data['comp_no']);
                Cookie::forever('userName', $userInfo['userName']);
                return json([
                    'error' => 0,
                    'message' => '登录成功！',
                    'data' => [
                        'userInfo' => $userInfo,
                        'token' => session_id(),
                    ]
                ]);


            }

        }else{

            return json(['error'=>1030,'message'=>'未开启企业微信功能']);
        }

    }
}
